原生容器支援:dotnet publish /p:UseCurrentRuntime
UseCurrentRuntime 是 MSBuild 屬性,用來在建置/發佈時自動推斷目前機器的 Runtime Identifier (RID),省去手動指定 -r linux-x64、win-x64、osx-arm64 等。容器發佈時可與 PublishContainer 搭配,簡化命令。
開始(需要安裝 Docker)
- 主控台/ASP.NET 專案一鍵發佈到容器映像
- dotnet publish -c Release -t:PublishContainer /p:UseCurrentRuntime=true
- 執行生成的映像
- docker run --rm -p 8080:8080 :
最小化 csproj 設定
<PropertyGroup>
<!-- 容器 -->
<ContainerImageName>myorg/myapp</ContainerImageName>
<ContainerImageTags>latest</ContainerImageTags>
<ContainerPort>8080</ContainerPort> <!-- ASP.NET 需對外暴露的 port -->
<ContainerBaseImage>mcr.microsoft.com/dotnet/aspnet:8.0</ContainerBaseImage>
<PublishTrimmed>true</PublishTrimmed>
<PublishAot>true</PublishAot> <!-- Native AOT(需支援平台 RID) -->
</PropertyGroup>
推送到自己的伺服器
- dotnet publish -t:PublishContainer -c Release /p:ContainerRegistry=你的伺服器 /p:ContainerImageName=myorg/myapp /p:ContainerImageTags=1.0.0;latest /p:UseCurrentRuntime=true
- 推送完成後即可 docker pull 你的伺服器/myorg/myapp:1.0.0
與 UseCurrentRuntime 的搭配
- UseCurrentRuntime=true 會將 RID 設為「當前機器」。用於容器時請確認你的目標容器是同類 OS:
- 要發佈 Linux 容器,但你在 Windows/macOS 上:請改用 -r linux-x64(或 linux-arm64),不要用 UseCurrentRuntime。
- 要發佈 Windows 容器:UseCurrentRuntime=true(在 Windows 上)即可推斷 win-x64/win-arm64。
命令組合舉例:
- Linux 容器 + AOT
- dotnet publish -c Release -t:PublishContainer -r linux-x64 /p:PublishAot=true /p:ContainerBaseImage=mcr.microsoft.com/dotnet/aspnet:8.0
- 本機 RID 容器
- dotnet publish -c Release -t:PublishContainer /p:UseCurrentRuntime=true
遇到的坑
- 發佈失敗(RID 不符 base image):請明確指定 -r 與相容的 ContainerBaseImage。
- 容器啟動但無法連線:確認 ContainerPort 與應用實際監聽埠一致,並在 docker run 時正確對映 -p。
- AOT 鏈結錯誤:移除 PublishAot 或補上必要的 DynamicDependency/Json Source Generator 設定。